//
//  XPMainTabController.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/9.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

class XPMainTabController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let tabBar = XPCustomTabBar()
        // 设置代理
        tabBar.composeBtnDelegate = self
        // 实现闭包
        tabBar.callBackClosure = { [weak self] in
            if XPUserAccountViewModel.defaultUserAccount.isLogin {
                self?.modalToComposeController()
            }
        }
        // tabBar是只读属性,利用KVC赋值
        setValue(tabBar, forKey: "tabBar")
        //添加控制器
        addAllMyControllers()
    }
    
    func modalToComposeController() {
        let nav = UINavigationController(rootViewController: XPComposeController())
        presentViewController(nav, animated: true, completion: nil)
    }
    
}

// MARK: - 为工具栏添加控制器的方法
extension XPMainTabController {
   private func addAllMyControllers() {
        let controllerArr = [XPHomeViewController(), XPMessageController(), XPDiscoverController(),XPProfileController()]
        let titleArr = ["首页", "消息", "发现", "我的"]
        let imageArr = ["tabbar_home", "tabbar_message_center", "tabbar_discover", "tabbar_profile"]
        
        for i in 0..<4 {
            addChildViewController(controllerArr[i], title: titleArr[i], imageName: imageArr[i])
        }
    }
    
   private func addChildViewController(childController: UIViewController, title: String, imageName: String) {
        //导航栏和工具栏的标题
        childController.title = title
        childController.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orangeColor()], forState: .Selected)
        childController.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(12)], forState: .Normal)
        //工具栏图片
        childController.tabBarItem.image = UIImage(named: imageName)
        childController.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.imageWithRenderingMode(.AlwaysOriginal)
        
        let nav = UINavigationController.init(rootViewController: childController)
        addChildViewController(nav)
    

    }
}

// MARK: - 自定义tabBar的代理方法
extension XPMainTabController: XPCustomTabBarDelegate {
    func didClickComposeButton() {
//        print("我是代理")
    }
}
